package com.xtsoft.platform.base.system.service.impl;


import com.xtsoft.core.service.impl.GenericServiceImpl;
import com.xtsoft.platform.base.system.domain.SysRole;
import com.xtsoft.platform.base.system.domain.SysUser;
import com.xtsoft.platform.base.system.domain.UserRole;
import com.xtsoft.platform.base.system.repository.SysRoleRepository;
import com.xtsoft.platform.base.system.repository.UserRoleRepository;
import com.xtsoft.platform.base.system.service.UserRoleService;
import com.xtsoft.platform.globe.Constants.Constants;
import com.xtsoft.platform.globe.enums.YesNo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("userRoleService")
public class UserRoleServiceImpl extends GenericServiceImpl<UserRole, String, UserRoleRepository> implements UserRoleService {

	@Autowired
	private UserRoleRepository userRoleRepository;
	@Autowired
	private SysRoleRepository sysRoleRepository;
	
	@Override
	public List<UserRole> findBySysRole(SysRole role) {
		// TODO Auto-generated method stub
		return userRoleRepository.findBySysRole(role);
	}

	@Override
	public boolean isRightSuperAdmin(SysUser sysUser, String clientIp) {
		// TODO Auto-generated method stub
		//根据状态和超级管理员角色名获取SysRole
		List<SysRole> role = sysRoleRepository.findByAliasAndState(Constants.AdminRole, YesNo.Yes.getIntValue());
		if(role==null) {
			log.info("获取角色信息失败",sysUser.getLoginId(), sysUser.getUsername(),clientIp);
		}
		//根据role获取用户角色
		List<UserRole> userRoles = userRoleRepository.findBySysRole(role.get(0));
		// 当Sort枚举为desc的时候就是降序排序 addSort的方法是QueryFilter自带的一个方法，根据传入进去的值作为条件来判断
		if (null == userRoles || userRoles.size() < 1) {
			log.info("获取用户信息失败",sysUser.getLoginId(), sysUser.getUsername(),
					clientIp);
		}
		List<SysUser> users = userRoles.stream().map(mapper -> mapper.getSysUser()).collect(Collectors.toList());
		return users.contains(sysUser);
	}

}
